<?php
include_once("fn.class.php");
class t
{
    //定义常量、变量
    const SECRET_KEY = '@4!@#$%@';
    public $cn;
    private $hn;
    private $dn;
    private $zd;
    private $zd1;
    private $zd2;
    private $zd3;
    private $key;
    private $tn;
    private $isautoadd;
    private $ku;
    private $lxupdates = 0; //连续update数
    private $maxlxupdates = 300; //最大连续修改数
    private $fields;
    public $sqlc;
    public $sql;
    protected $parentpath = "";


    //构造函数,入口函数
    public function t($hn, $username, $password, $dn = "", $tn = "")
    {
        $this->set($hn, $username, $password, $dn, $tn);
    }

    public function set($hn, $username, $password, $dn = "", $tn = "")
    {
        $this->hn = $hn;
        $this->cn = mysql_connect($hn, $username, $password);
        self::setutf8();
        if ($dn != "") {
            $this->dn = $dn;
            mysql_select_db($dn, $this->cn) or die("error: " . mysql_error());
        }
        if ($tn != "") {
            $this->tn = $tn;
        }
    }

    public function setmaxlxupdates($value)
    {
        if ($value >= 0) {
            $this->maxlxupdates = $value;
        }
    }

    public function connect($hn, $username, $password, $dn = "")
    {
        if ($dn) $this->dn = $dn;
        self::set($hn, $username, $password);
        self::setutf8();
    }

    public function select_db($dn)
    {
        $this->dn = $dn;
        mysql_select_db($dn, $this->cn) or die("error: " . mysql_error());
    }

    public function selectdb($dn)
    {
        $this->dn = $dn;
        mysql_select_db($dn, $this->cn) or die("error: " . mysql_error());
    }

    public function selecttb($tn)
    {
        $this->tn = $tn;
    }

    public function getzd($tn = "")
    {
        if ($tn != "") $this->tn = $tn;
        $this->getkey($this->tn);
        $return = join(",", $this->zd);
        return $return;
    }

    public function setutf8()
    {
        mysql_query("set character set 'utf8'");
        mysql_query("set names 'utf8'");
    }

    public function setgb2312()
    {
        mysql_query("set character set 'GB2312'");
        mysql_query("set names 'GB2312'");
    }

    public function sql($sql, $bug = 0)
    {
        mysql_select_db($this->dn, $this->cn); // or die("error: ". mysql_error())
        $ku = mysql_query($sql, $this->cn);
        if ($bug && mysql_error() != "") echo "\r\n" . mysql_error();
        $this->ku = $ku;
        return $ku;
    }

    public function execute($sql, $bug = 0)
    {
        mysql_select_db($this->dn);
        mysql_query($sql, $this->cn);
        $this->sql = $sql;
        if ($bug || mysql_error() != "") $this->sql .= "\r\n error:" . mysql_error()."\r\n\r\n".self::goodsql($sql);
    }

    public function sqlku($sql, $bug = 0)
    {
        mysql_select_db($this->dn);
        $this->ku = $ku = mysql_query($sql, $this->cn);
        if ($bug && mysql_error() != "") echo "\r\n" . mysql_error();
        return $ku;
    }

    public function sqlkuarray($sql, $bug = 0)
    {
        mysql_select_db($this->dn);
        $this->ku = $ku = mysql_query($sql, $this->cn);
        if ($bug && mysql_error() != "") echo "\r\n" . mysql_error();
        $array = array();
        //if(mysql_num_rows($ku)<=0) return array();
        while ($rs = mysql_fetch_array($ku)) {
            $array[] = $rs;
        }

        $newarr = array();
        for ($i = 0; $i < count($array); $i++) {
            foreach ($array[$i] as $k => $v) {
                if (is_int($k)) continue;
                $newarr[$i][$k] = $v;
            }
        }

        if (count($newarr[0]) == 1) {
            $newarrtemp = $newarr;
            $newarr = array();
            for ($i = 0; $i < count($newarrtemp); $i++) {
                foreach ($newarrtemp[$i] as $k => $v) {
                    $newarr[] = $v;
                }
            }
        }
        //if (count($newarr) == 1) $newarr = current($newarr);
        return $newarr;
    }

    public function sqlone($sql, $bug = 0)
    {
        mysql_select_db($this->dn);
        $this->ku = $ku = mysql_query($sql, $this->cn);
        $this->sql = $sql;
        //if ($bug || mysql_error() != "") $this->sql .= "\r\n" . mysql_error();
        $r = @mysql_fetch_array($ku);
        return $r;
    }

    public function sqlvalue($sql, $bug = 0)
    {
        mysql_select_db($this->dn);
        $this->ku = $ku = mysql_query($sql, $this->cn);
        if ($bug || mysql_error() != "") $this->sql .= "\r\n" . mysql_error();
        if (@mysql_num_rows($ku) > 0) {
            $array = @mysql_fetch_array($ku);
            $newarr = array();

            if (is_array($array[0])) {
                for ($i = 0; $i < count($array); $i++) {
                    foreach ($array[$i] as $k => $v) {
                        if (is_int($k)) continue;
                        $newarr[$i][$k] = $v;
                    }
                }
            } else {
                foreach ($array as $k => $v) {
                    if (is_int($k)) continue;
                    $newarr[] = $v;
                }
            }

            if (is_array($newarr[0])) {
                $newarrtemp = $newarr;
                $newarr = array();
                for ($i = 0; $i < count($newarrtemp); $i++) {
                    foreach ($newarrtemp[$i] as $k => $v) {
                        $newarr[] = $v;
                    }
                }
            }
            if (count($newarr) == 1) $newarr = current($newarr);
        } else {
            $newarr = 0;
        }
        $return = ($newarr == 0) ? 0 : $newarr;
        $this->sql .= "\r\n".$return;
        return $return;
    }


    public function writetobd()
    {
        $cn2 = mssql_connect("127.0.0.1", "sa", "159456");
        mssql_select_db("yangzs", $cn2);
        if ($this->hn) mssql_query("update copy set text = '" . $this->hn . "' where dh = 'myhn'", $cn2);
        if ($this->dn) mssql_query("update copy set text = '" . $this->dn . "' where dh = 'mydn'", $cn2);
        if ($this->tn) {
            self::getkey($this->tn);
            mssql_query("update copy set text = '" . $this->tn . "' where dh = 'mytn'", $cn2);
            mssql_query("update copy set text = '" . $this->zd1 . "' where dh = 'zd1'", $cn2);
            mssql_query("update copy set text = '" . $this->zd2 . "' where dh = 'zd2'", $cn2);
            mssql_query("update copy set text = '" . $this->zd3 . "' where dh = 'zd3'", $cn2);
            mssql_query("update copy set text = '" . $this->key . "' where dh = 'key'", $cn2);
            mssql_query("update copy set text = '" . $this->isautoadd . "' where dh = 'autoadd' or dh = 'isautoadd'", $cn2);
            mssql_query("update copy set text = '" . join(",", $this->zd) . "' where dh = 'zd'", $cn2);
            $sql = "update copy set text = '" . $this->zd2 . "=''\$" . $this->zd2 . "''," . $this->zd3 . "=''\$" . $this->zd3 . "''' where dh = 'where'";
            mssql_query($sql, $cn2);
        }
    }

    public function settn($tn)
    {
        $this->tn = $tn;
        self::writetobd();
    }

    public function getkey($tn)
    {

        $zd = array();
        $this->fields();
        mysql_select_db($this->dn) or die("error: " . mysql_error());
        $result = $this->sql("select * from $tn limit 0,1", 1);
        for ($i = 0; $i < mysql_num_fields($result); $i++) {
            if ($i === 0) $this->zd1 = mysql_field_name($result, $i);
            if ($i === 1) $this->zd2 = mysql_field_name($result, $i);
            if ($i === 2) $this->zd3 = mysql_field_name($result, $i);

            if (preg_match(" / primary_key / ", mysql_field_flags($result, $i))) {
                if (preg_match(" / auto_increment / ", mysql_field_flags($result, $i))) {
                    $this->isautoadd = 1;
                } else {
                    $this->isautoadd = 0;
                }
                $return = mysql_field_name($result, $i);
                $this->key = $return;
            }
            $zd[] = mysql_field_name($result, $i);
        }
        $this->zd = $zd;

        return $this->key;
    }



    public function fields(){
        global $t;
        if ($tn == "") $tn = $this->tn;
        mysql_select_db($this->dn) or die("error: " . mysql_error());
        $result = $this->sql("SHOW FULL FIELDS FROM $tn", 1);
        $arr=array();
        while($rs=mysql_fetch_array($result)){
            $arr[$rs['Field']]['type']=$rs['Type'];
            $arr[$rs['Field']]['key']=$rs['Key'];
            $arr[$rs['Field']]['auto']=$rs['Extra'];
            $arr[$rs['Field']]['null']=$rs['Null'];
            $arr[$rs['Field']]['default']=(preg_match("/int/ ",$arr[$rs['Field']]['type']))?0:$rs['Default'];
            $arr[$rs['Field']]['default']=(preg_match("/float\([0-9]+\,([0-9]+)\)/x",$arr[$rs['Field']]['type'],$nn))?"0.".str_repeat("0",$nn[1]):$arr[$rs['Field']]['default'];
        }
        $this->fields=$arr;
        return $arr;
    }

    public function rkarray($tablen, $zd, $where, $param = array(), $data)
    {
        foreach ($data as $key => $v) {
            $return = self::rk($tablen, $zd, $where, $param, $v);
            if ($return == "break") break;
        }
    }

    public function listku()
    {
        $kutemp = $this->ku;
        echo "\r\n";
        while ($rs = mysql_fetch_array($kutemp)) {
            for ($i = 0; $i < mysql_num_fields($kutemp); $i++) {
                echo "[" . preg_replace(" / (\r | \n) +/m", " ", trim($rs[$i])) . "]\t    ";
            }
            echo "\r\n";
        }
    }


    public function rk($tablen, $zd, $where, $param = array(), $data = array())
    {
        $this->tn = $tablen;
        $this->getkey($this->tn);
        extract($param);
        self::mextract($data);
        $zdarr = preg_split(" /\s*,\s*/x", $zd);
        $pczd = preg_split(" /\s*,\s*/x", $pczd);
        $qzsxarray=(isset($qzsxarray))?$qzsxarray:array();
        if (!empty($keyarray)) {
            foreach ($keyarray as $k2 => $v2) {
                $GLOBALS[$k2] = $GLOBALS[$v2]; //keyarray 的参数例子 'id'=>'xxid' 非  'id'=>'$xxid'
            }
        }


        $fields = mysql_list_fields($this->dn, $this->tn, $this->cn);
        $columns = mysql_num_fields($fields);
        $fieldsarray = array();
        for ($i = 0; $i < $columns; $i++) {
            $fieldsarray[] = mysql_field_name($fields, $i);
        }

        $where = preg_replace(" /\\\$([a-zA-Z0-9_]+)/isxe", "str_replace(\"'\",\"''\",\$GLOBALS['\\1'])", $where);
        $sql = "select * from $tablen limit 0,1";
        if ($bug) echo "\r\n<br>" . $sql;
        $r = self::sqlone($sql);
        $sql0 = $sql2 = $sql3 = "";
        foreach ($fieldsarray as $k => $fd) {

            if ($zd != "" && !in_array(trim($fd), $zdarr) || in_array($fd, $pczd)) {
                continue;
            }

            $this->fields[$fd]['default']=(preg_match("/int|float/",$this->fields[$fd]['type'])&&$this->fields[$fd]['null'] == "NO")?0:$this->fields[$fd]['default'];
            $GLOBALS[$fd]=(!isset($GLOBALS[$fd])&&preg_match("/int|float/",$this->fields[$fd]['type']))?0:$GLOBALS[$fd];
            $GLOBALS[$fd]=($GLOBALS[$fd]==""&&preg_match("/int|float/",$this->fields[$fd]['type']))?0:$GLOBALS[$fd];
            $GLOBALS[$fd]=(($GLOBALS[$fd]==""||!isset($GLOBALS[$fd]))&&$this->fields[$fd]['type']=="date")?date("Y-m-d"):$GLOBALS[$fd];
            $GLOBALS[$fd]=(($GLOBALS[$fd]==""||!isset($GLOBALS[$fd]))&&$this->fields[$fd]['type']=="datetime")?date("Y-m-d H:i:s"):$GLOBALS[$fd];
            $GLOBALS[$fd]=(trim($GLOBALS[$fd])=='null')?"":$GLOBALS[$fd];
            if ($this->fields[$fd]['key'] != "PRI" || $this->fields[$fd]['auto'] != "auto_increment") {
                if ($this->fields[$fd]['null'] == "NO" && isset($this->fields[$fd]['default']) && trim($GLOBALS[$fd]) == "") {
                    $sql0 .= "`$fd`,";
                    $sql2 .= "'" . self::clf($this->fields[$fd]['default']) . "',";
                } else {
                    $sql0 .= "`$fd`,";
                    $sql2 .= "'" . self::clf($GLOBALS[$fd]) . "',";
                }
            }


            if ((!Fn::isnull($GLOBALS[$fd]) || isset($this->fields[$fd]['default']))) {
                if ($this->fields[$fd]['key'] != "PRI" || $this->fields[$fd]['auto'] != "auto_increment") {
                    if ($this->fields[$fd]['null'] == "NO" && isset($this->fields[$fd]['default']) && trim($GLOBALS[$fd]) == "") {
                        $sql3 .= "`$fd`='" .self::clf($this->fields[$fd]['default']) . "',";
                    } else {
                        $sql3 .= "`$fd`='" . self::clf($GLOBALS[$fd]) . "',";
                    }
                }
            }
        }

        $sql0 = substr($sql0, 0, -1);
        $sql2 = substr($sql2, 0, -1);
        $sql3 = substr($sql3, 0, -1);
        mysql_select_db($this->dn);

        $sql = "select * from $tablen where $where limit 0,1";
        $r = self::sqlone($sql);
        $this->sqlc = $sql;

        if ($r[$this->key] > 0) {
            if ($sql3 != "") {
                $sql = "update $tablen set $sql3 where " . $this->key . "=" . $r[$this->key];
                if ($bug) echo "\r\n<br>" . self::goodsql($sql);
                $this->execute($sql, $bug);
                $this->lxupdates++;
                if ($this->lxupdates >= $this->maxlxupdates) {
                    $this->lxupdates = 0;
                    return "break";
                }
            }
            $return = $r[$this->key];
        } elseif ($insert == 1) {
            if ($sql0 != "" && $sql2 != "") {
                $sql = "insert into $tablen ($sql0) values ($sql2)";
                if ($bug) echo "\r\n<br>" . $sql;
                $this->execute($sql, $bug);
                $sql2 = "select " . $this->key . " from " . $this->tn . " order by " . $this->key . " desc limit 0,1";
                $r3 = self::sqlone($sql2);
                $return = $r3[$this->key];
                $this->sql=$this->sql."\r\n".self::goodsql($sql)."\r\n".$return;
            } else {
                $return = 0;
            }
            $this->lxupdates = 0;
        } else {
            $return = 0;
        }

        if ($backfun != "") {
            $backfun($return);
        }

        //r($sql);
        //if ($bug) echo "\r\n返回:" . $return . "\r\n";
        return $return;

    }


    //静态方法
    static public function mextract($arr)
    {
        if (!empty($arr) && is_array($arr)) {
            foreach ($arr as $key => $value) {
                $GLOBALS[$key] = $value;
            }
        }
    }

    static public function goodsql($sql){
        if(preg_match("/(insert\s+into.*)\((.*)\)\s*values\s*\((.*)\'\)/Uisx",$sql,$nn)){
            $s=$nn[1]."\r\n(";
            $k=preg_split("/\,/",$nn[2]);
            $v=preg_split("/\'\,\'/",$nn[3]);
            for($i=0;$i<count($k);$i++){
                $s.=$k[$i]."=>".$v[$i]."\r\n";
            }
            $s.="\r\n)";
            return $s;
        }
        return $sql;
    }

    function clf($str){
        if (!get_magic_quotes_gpc()){
            $str=addcslashes($str);
        }
        //$str=str_replace("'", "''", $str);
        return $str;
    }

}

?>